package com.runtime.hongyunmanage.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/oss")
public class OssController {

    @Value("${upload.path:static/image/productimage/}")
    private String uploadPath;

    @Value("${category.upload.path:static/image/categoryimage/}")
    private String categoryUploadPath;
    //商品图片文件上传
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return new Result(Code.SAVE_ERR, null, "上传文件为空");
            }

            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource resource = resolver.getResource("classpath:/" + uploadPath);
            File dir = resource.getFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String fileName = UUID.randomUUID().toString() +
                    "." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            File dest = new File(dir, fileName);
            file.transferTo(dest);

            String url = "/productimage/" + fileName;
            return new Result(Code.SAVE_OK, url, "上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Code.SAVE_ERR, null, "上传失败");
        }
    }

    //商品图片文件删除
    @DeleteMapping("/delete/{fileName}")
    public Result delete(@PathVariable String fileName) {
        try {
            if (fileName == null || fileName.isEmpty()) {
                return new Result(Code.DELETE_ERR, null, "文件名不能为空");
            }

            // 构建文件路径
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource resource = resolver.getResource("classpath:/" + uploadPath);
            File dir = resource.getFile();
            File fileToDelete = new File(dir, fileName);

            // 检查文件是否存在
            if (!fileToDelete.exists()) {
                return new Result(Code.DELETE_ERR, null, "文件不存在");
            }

            // 检查是否为文件（防止目录被删除）
            if (!fileToDelete.isFile()) {
                return new Result(Code.DELETE_ERR, null, "指定路径不是文件");
            }

            // 执行删除
            boolean success = fileToDelete.delete();
            if (success) {
                return new Result(Code.DELETE_OK, null, "删除成功");
            } else {
                return new Result(Code.DELETE_ERR, null, "删除失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Code.DELETE_ERR, null, "删除过程中发生错误");
        }
    }


    // 分类图片文件上传
    @PostMapping("/category/upload")
    public Result uploadCategoryImage(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return new Result(Code.SAVE_ERR, null, "上传文件为空");
            }

            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource resource = resolver.getResource("classpath:/" + categoryUploadPath);
            File dir = resource.getFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String fileName = UUID.randomUUID().toString() +
                    "." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            File dest = new File(dir, fileName);
            file.transferTo(dest);

            String url = "/categoryimage/" + fileName;
            return new Result(Code.SAVE_OK, url, "上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Code.SAVE_ERR, null, "上传失败");
        }
    }

    // 分类图片文件删除
    @DeleteMapping("/category/delete/{fileName}")
    public Result deleteCategoryImage(@PathVariable String fileName) {
        try {
            if (fileName == null || fileName.isEmpty()) {
                return new Result(Code.DELETE_ERR, null, "文件名不能为空");
            }

            // 构建文件路径
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource resource = resolver.getResource("classpath:/" + categoryUploadPath);
            File dir = resource.getFile();
            File fileToDelete = new File(dir, fileName);

            // 检查文件是否存在
            if (!fileToDelete.exists()) {
                return new Result(Code.DELETE_ERR, null, "文件不存在");
            }

            // 检查是否为文件（防止目录被删除）
            if (!fileToDelete.isFile()) {
                return new Result(Code.DELETE_ERR, null, "指定路径不是文件");
            }

            // 执行删除
            boolean success = fileToDelete.delete();
            if (success) {
                return new Result(Code.DELETE_OK, null, "删除成功");
            } else {
                return new Result(Code.DELETE_ERR, null, "删除失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Code.DELETE_ERR, null, "删除过程中发生错误");
        }
    }
}